package com.turbo.cloud.starter.sequence;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * Redis 自增序列，生成业务唯一主键
 *
 * @author zhangluning
 */
@Component
@RequiredArgsConstructor
public class RedisIncrSequenceFactory implements SequenceFactory {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    private final RedisTemplate redisTemplate;

    @Override
    public String nextValue(String redisKey) {
        return nextValue(redisKey, 0);
    }

    @Override
    public String nextValue(String redisKey, int sequenceNoLength) {
        long sequenceNo = redisTemplate.opsForValue().increment(redisKey);
        return formatSequenceNo(sequenceNo, sequenceNoLength);
    }

    @Override
    public String nextValueByDaily(String redisKey) {
        return nextValueByDaily(redisKey, 0);
    }

    @Override
    public String nextValueByDaily(String redisKey, int sequenceNoLength) {
        String today = LocalDate.now().format(FORMATTER);
        String redisKeyByDaily = redisKey + ":" + today;
        long sequenceNo = redisTemplate.opsForValue().increment(redisKeyByDaily);

        return formatSequenceNo(sequenceNo, sequenceNoLength);
    }

    /**
     * 序列号格式化
     *
     * @param sequenceNo       序列号
     * @param sequenceNoLength 序列号补位长度
     */
    private String formatSequenceNo(long sequenceNo, int sequenceNoLength) {
        String sequenceNoStr = sequenceNo + "";
        if (sequenceNoLength > 0) {
            sequenceNoStr = String.format("%0" + sequenceNoLength + "d", sequenceNo);
        }
        return sequenceNoStr;
    }
}
